{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <h2>奖助学金申请</h2>
        
        {% if current_user.role == 'student' %}
            <div class="card mt-4">
                <div class="card-header">
                    <h4>基础信息</h4>
                </div>
                <div class="card-body">
                    <form method="POST" action="{{ url_for('submit_scholarship') }}" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        
                        <!-- 基本信息字段 -->
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">姓名</label>
                                <input type="text" class="form-control" name="real_name" value="{{ current_user.real_name }}" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">学号</label>
                                <input type="text" class="form-control" name="username" value="{{ current_user.username }}" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">性别 <span class="text-danger">*</span></label>
                                <select class="form-select" name="gender" required>
                                    <option value="">请选择性别</option>
                                    <option value="男">男</option>
                                    <option value="女">女</option>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">出生日期 <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="birth_date" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">民族 <span class="text-danger">*</span></label>
                                <select class="form-select" name="ethnicity" required>
                                    <option value="">请选择民族</option>
                                    <option value="汉族">汉族</option>
                                    <option value="壮族">壮族</option>
                                    <option value="满族">满族</option>
                                    <option value="回族">回族</option>
                                    <option value="苗族">苗族</option>
                                    <option value="维吾尔族">维吾尔族</option>
                                    <option value="彝族">彝族</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">身份证件号 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="id_number" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-8 mb-3">
                                <label class="form-label">籍贯 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="hometown" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">户口性质 <span class="text-danger">*</span></label>
                                <select class="form-select" name="household_type" required>
                                    <option value="">请选择户口性质</option>
                                    <option value="农业户口">农业户口</option>
                                    <option value="非农业户口">非农业户口</option>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">政治面貌 <span class="text-danger">*</span></label>
                                <select class="form-select" name="political_status" required>
                                    <option value="">请选择政治面貌</option>
                                    <option value="中国共产主义青年团员">中国共产主义青年团员</option>
                                    <option value="中国共产党党员">中国共产党党员</option>
                                    <option value="群众">群众</option>
                                </select>
                            </div>
                        </div>

                        <!-- 学籍信息 -->
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">学院 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="college" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">专业 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="major" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">班级 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="class_name" required>
                            </div>
                        </div>

                        <!-- 将学习情况（新）入主表单内 -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <h4>学习情况</h4>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">必修课门数</label>
                                        <input type="number" class="form-control" name="required_courses" min="0">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">必修课及格门数</label>
                                        <input type="number" class="form-control" name="pass_courses" min="0">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">总人数</label>
                                        <input type="number" class="form-control" name="total_students" min="0">
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">成绩排名</label>
                                        <input type="number" class="form-control" name="rank" min="1">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">实行综合测评排名</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="ranking_type" value="normal">
                                            <label class="form-check-label">正常</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="ranking_type" value="special">
                                            <label class="form-check-label">专延长</label>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">排名类型</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="rank_scope" value="major">
                                            <label class="form-check-label">按专业</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="rank_scope" value="major_direction">
                                            <label class="form-check-label">按专业方向</label>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label">排名说明</label>
                                        <textarea class="form-control" name="rank_description" rows="3"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 奖学金信息部分移入主表单 -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <h4>奖学金信息</h4>
                            </div>
                            <div class="card-body">
                                <div id="scholarship-container">
                                    <div class="row mb-3 scholarship-row">
                                        <div class="col-md-4">
                                            <label class="form-label">受理部门</label>
                                            <input type="text" class="form-control" name="departments[]" value="国家奖学金">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">金额</label>
                                            <input type="number" class="form-control" name="amounts[]" value="8000">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">评定周期</label>
                                            <input type="text" class="form-control" name="periods[]" value="2024-2025学年">
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label">&nbsp;</label>
                                            <button type="button" class="btn btn-danger btn-sm d-block w-100" onclick="removeScholarship(this)">删除</button>
                                        </div>
                                    </div>
                                </div>
                                <div class="text-center mt-3">
                                    <button type="button" class="btn btn-secondary" onclick="addScholarship()">
                                        <i class="bi bi-plus"></i> 添加奖学金信息
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- 申请理由部入主表单 -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <h4>申请理由</h4>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <textarea class="form-control" name="application_reason" rows="5"></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- 附件上传部分移入主表单 -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <h4>附件上传</h4>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <input type="file" class="form-control" name="attachments[]" multiple>
                                    <div class="form-text">可以上传多个文件，支持PDF、Word、图片等格式</div>
                                </div>
                                <div id="file-list" class="mt-3">
                                    <!-- 已上传的文件列表将在这里显示 -->
                                </div>
                            </div>
                        </div>

                        <!-- 在校期间主要获奖情况移入主表单 -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <h4>在校期间主要获奖情况</h4>
                            </div>
                            <div class="card-body">
                                <div id="awards-container">
                                    <div class="row mb-3 award-row">
                                        <div class="col-md-3">
                                            <label class="form-label">奖项名称</label>
                                            <input type="text" class="form-control" name="award_names[]" placeholder="请输入奖项名称">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">获奖类别</label>
                                            <select class="form-select" name="award_type[]">
                                                <option value="">请选择奖项类别</option>
                                                <option value="省级">省级</option>
                                                <option value="校级">校级</option>
                                                <option value="院级">院级</option>
                                                <option value="其他">其他</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">获奖日期</label>
                                            <input type="date" class="form-control" name="award_date[]">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">获奖年度</label>
                                            <select class="form-select" name="award_year[]">
                                                <option value="2023-2024">2023-2024</option>
                                                <option value="2024-2025">2024-2025</option>
                                            </select>
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label">&nbsp;</label>
                                            <button type="button" class="btn btn-danger btn-sm d-block w-100" onclick="removeAward(this)">删除</button>
                                        </div>
                                    </div>
                                </div>
                                <div class="text-center mt-3">
                                    <button type="button" class="btn btn-secondary" onclick="addAward()">
                                        <i class="bi bi-plus"></i> 添加获奖记录
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- 提交按钮 -->
                        <div class="card mt-4">
                            <div class="card-body">
                                <button type="submit" class="btn btn-primary btn-lg w-100">提交申请</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 历史记录部分放在表单外 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>我的申请记录</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>申请时间</th>
                                <th>奖助学金类型</th>
                                <th>申请状态</th>
                                <th>附件</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in scholarship_records %}
                            <tr>
                                <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>{{ record.type }}</td>
                                <td>
                                    {% if record.status == 'pending' %}
                                        <span class="badge bg-warning">待审核</span>
                                    {% elif record.status == 'approved' %}
                                        <span class="badge bg-success">已通过</span>
                                    {% else %}
                                        <span class="badge bg-danger">已驳回</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_scholarship_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        {% endif %}

        {% if current_user.role == 'teacher' %}
        <div class="card mt-4">
            <div class="card-header">
                <h4>待审核的奖学金申请</h4>
            </div>
            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th>申请时间</th>
                            <th>学生姓名</th>
                            <th>学号</th>
                            <th>奖学金类型</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for record in scholarship_records %}
                        {% if record.status == 'pending' %}
                        <tr>
                            <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                            <td>{{ record.user.real_name }}</td>
                            <td>{{ record.user.username }}</td>
                            <td>
                                {% if record.scholarship_info %}
                                    {% for info in record.scholarship_info %}
                                        {{ info.department }}<br>
                                    {% endfor %}
                                {% endif %}
                            </td>
                            <td>
                                <span class="badge bg-warning">待审核</span>
                            </td>
                            <td>
                                <button type="button" class="btn btn-success btn-sm" onclick="approveScholarship({{ record.id }})">通过</button>
                                <button type="button" class="btn btn-danger btn-sm" onclick="rejectScholarship({{ record.id }})">驳回</button>
                                {% if record.attachments %}
                                    <button type="button" class="btn btn-info btn-sm" onclick="viewAttachments({{ record.id }})">查看附件</button>
                                {% endif %}
                            </td>
                        </tr>
                        {% endif %}
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 添加已审核记录表格 -->
        <div class="card mt-4">
            <div class="card-header">
                <h4>已审核的奖学金申请</h4>
            </div>
            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th>申请时间</th>
                            <th>学生姓名</th>
                            <th>学号</th>
                            <th>奖学金类型</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for record in scholarship_records %}
                        {% if record.status != 'pending' %}
                        <tr>
                            <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                            <td>{{ record.user.real_name }}</td>
                            <td>{{ record.user.username }}</td>
                            <td>
                                {% if record.scholarship_info %}
                                    {% for info in record.scholarship_info %}
                                        {{ info.department }}<br>
                                    {% endfor %}
                                {% endif %}
                            </td>
                            <td>
                                {% if record.status == 'approved' %}
                                    <span class="badge bg-success">已通过</span>
                                {% else %}
                                    <span class="badge bg-danger">已驳回</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if record.attachments %}
                                    <button type="button" class="btn btn-info btn-sm" onclick="viewAttachments({{ record.id }})">查看附件</button>
                                {% endif %}
                            </td>
                        </tr>
                        {% endif %}
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 添加JavaScript代码 -->
        <script>
        // 将函数定义移到全局作用域
        window.approveScholarship = function(id) {
            if (!confirm('确定要通过这条申请记录吗？')) {
                return;
            }
            
            const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
            
            fetch(`/approve_scholarship/${id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-Token': token
                },
                credentials: 'same-origin'
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert('审核通过成功！');
                    window.location.reload();
                } else {
                    alert('操作失败：' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请重试');
            });
        };

        window.rejectScholarship = function(id) {
            if (!confirm('确定要驳回这条申请记录吗？')) {
                return;
            }
            
            const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
            
            fetch(`/reject_scholarship/${id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-Token': token
                },
                credentials: 'same-origin'
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert('驳回成功！');
                    window.location.reload();
                } else {
                    alert('操作失败：' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请重试');
            });
        };

        window.viewAttachments = function(id) {
            window.location.href = `/download_scholarship_proof/${id}`;
        };

        // 确保在页面加载完成后绑定事件
        document.addEventListener('DOMContentLoaded', function() {
            // 如果需要其他初始化代码，可以放在这里
            console.log('Scholarship page scripts loaded');
        });
        </script>
        {% endif %}
    </div>
</div>
{% endblock %} 

{% block scripts %}
{{ super() }}
<script>
function addAward() {
    const container = document.getElementById('awards-container');
    const template = `
        <div class="row mb-3 award-row">
            <div class="col-md-3">
                <label class="form-label">奖项名称</label>
                <input type="text" class="form-control" name="award_names[]" placeholder="请输入奖项名称" required>
            </div>
            <div class="col-md-3">
                <label class="form-label">获奖类别</label>
                <select class="form-select" name="award_type[]" required>
                    <option value="">请选择奖项类别</option>
                    <option value="省级">省级</option>
                    <option value="校级">校级</option>
                    <option value="院级">院级</option>
                    <option value="其他">其他</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">获奖日期</label>
                <input type="date" class="form-control" name="award_date[]" required>
            </div>
            <div class="col-md-2">
                <label class="form-label">获奖年度</label>
                <select class="form-select" name="award_year[]" required>
                    <option value="2023-2024">2023-2024</option>
                    <option value="2024-2025">2024-2025</option>
                </select>
            </div>
            <div class="col-md-1">
                <label class="form-label">&nbsp;</label>
                <button type="button" class="btn btn-danger btn-sm d-block w-100" onclick="removeAward(this)">删除</button>
            </div>
        </div>
    `;
    
    container.insertAdjacentHTML('beforeend', template);
}

function removeAward(button) {
    const row = button.closest('.award-row');
    row.remove();
}

document.querySelector('input[name="attachments[]"]').addEventListener('change', function(e) {
    const fileList = document.getElementById('file-list');
    fileList.innerHTML = '';
    
    Array.from(this.files).forEach(file => {
        const fileItem = document.createElement('div');
        fileItem.className = 'mb-2';
        fileItem.innerHTML = `
            <i class="bi bi-file-earmark"></i>
            ${file.name}
            <small class="text-muted">(${(file.size / 1024 / 1024).toFixed(2)} MB)</small>
        `;
        fileList.appendChild(fileItem);
    });
});

function addScholarship() {
    const container = document.getElementById('scholarship-container');
    const template = `
        <div class="row mb-3 scholarship-row">
            <div class="col-md-4">
                <label class="form-label">受理部门</label>
                <input type="text" class="form-control" name="departments[]">
            </div>
            <div class="col-md-3">
                <label class="form-label">金额</label>
                <input type="number" class="form-control" name="amounts[]">
            </div>
            <div class="col-md-4">
                <label class="form-label">评定周期</label>
                <input type="text" class="form-control" name="periods[]">
            </div>
            <div class="col-md-1">
                <label class="form-label">&nbsp;</label>
                <button type="button" class="btn btn-danger btn-sm d-block w-100" onclick="removeScholarship(this)">删除</button>
            </div>
        </div>
    `;
    
    container.insertAdjacentHTML('beforeend', template);
}

function removeScholarship(button) {
    const row = button.closest('.scholarship-row');
    if (document.querySelectorAll('.scholarship-row').length > 1) {
        row.remove();
    } else {
        alert('至少需要保留一行奖学金信息');
    }
}
</script>
{% endblock %} 